package com.yj.springbootstudy.mulThread.imooc;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁写案例
 *
 * 创建两个线程，线程名称分别为 t1，t2；
 * 线程 t1 进行读操作，获取到读锁之后，沉睡 5000 毫秒；
 * 线程 t2 进行写操作；
 * 开启 t1，1000 毫秒后开启 t2 线程；
 * 运行程序，观察结果。
 */
public class Demo05 {
    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    int i;

    public String readI(){
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "获取到读锁！");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        } finally {
            lock.readLock().unlock();
        }
        return i+"";
    }

    public void writeI(){
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "获取到写锁！");
            i++;
        }  finally {
            lock.writeLock().unlock();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Demo05 demo05 = new Demo05();
        new Thread(()->{
           demo05.readI();
        },"t1").start();
        Thread.sleep(1000);
        new Thread(()->{
            demo05.writeI();
        },"t2").start();
    }


}


